package com.ruoyi.web.controller.system;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.AttendanceRecord;
import com.ruoyi.system.service.IAttendanceRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;

import org.springframework.web.bind.annotation.*;




@RestController
@RequestMapping("/system/record")
public class AttendanceRecordController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(AttendanceRecordController.class);

    @Autowired
    private IAttendanceRecordService attendanceRecordService;




    @Log(title = "上班打卡", businessType = BusinessType.INSERT)
    @PostMapping("/checkIn")
    public AjaxResult checkIn()
    {
        // 获取当前用户ID
        Long userId = SecurityUtils.getUserId();
        System.out.println("当前登录的用户ID是：" + userId);

        // 检查今天是否已经打卡
        AttendanceRecord todayRecord = attendanceRecordService.selectTodayRecordByUserId(userId);
        if (todayRecord != null) {
            return error("今日已打卡，请勿重复操作");
        }

        // 创建打卡记录
        AttendanceRecord record = new AttendanceRecord();
        record.setUserId(userId);
        Date checkInTime = new Date();
        record.setCheckInTime(new Date());
        record.setCheckInMethod("MANUAL");
        record.setWorkDate(new Date()); // 自动设置当前日期
//        record.setStatus("LATE");
        LocalTime normalStartTime = LocalTime.of(9, 0);
        LocalTime LateLimitTime = LocalTime.of(9, 30);

        LocalTime currentTime = checkInTime.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
        if (currentTime.isAfter(LateLimitTime)) {
            record.setStatus("ABSENT");
        }
        else if(currentTime.isAfter(normalStartTime)&&currentTime.isBefore(LateLimitTime)){
            record.setStatus("LATE");
        }
        else {
            record.setStatus("NORMAL");
        }
        int result = attendanceRecordService.insertAttendanceRecord(record);
        if (result > 0) {
            // 返回包含完整状态信息的对象
            return AjaxResult.success("打卡成功", record);
        }
        return error("打卡失败");

//        return toAjax(attendanceRecordService.insertAttendanceRecord(record));
    }

    /**
     * 下班打卡
     */
    @Log(title = "下班打卡", businessType = BusinessType.UPDATE)
    @PostMapping("/checkOut")
    public AjaxResult checkOut()
    {
        // 获取当前用户ID
        Long userId = SecurityUtils.getUserId();

        // 查询今天的打卡记录
        AttendanceRecord todayRecord = attendanceRecordService.selectTodayRecordByUserId(userId);
        if (todayRecord == null) {
            return error("今日未打卡上班");
        }

        if (todayRecord.getCheckOutTime() != null) {
            return error("今日已打卡下班");
        }

        // 更新下班时间
        Date checkInTime = new Date();
        Date checkOutTime = new Date();
        todayRecord.setCheckOutTime(checkOutTime);
        todayRecord.setCheckOutMethod("MANUAL");
// 设置正常下班时间，假设是 18:00
        LocalTime normalEndTime = LocalTime.of(18, 0);
        LocalTime normalStartTime = LocalTime.of(9, 0);
        LocalTime LateLimitTime = LocalTime.of(9, 30);

        LocalTime currentTime = checkInTime.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
        LocalTime currentEndTime = checkOutTime.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
        if (currentEndTime.isBefore(normalEndTime)&&currentTime.isBefore(normalStartTime)) {
            todayRecord.setStatus("EARLY_LEAVE");
        }
        else if(currentTime.isAfter(LateLimitTime) ){
            todayRecord.setStatus("ABSENT");


    }else {
            // 如果上班未迟到，且下班未早退，状态为正常
            if ("NORMAL".equals(todayRecord.getStatus())) {
                todayRecord.setStatus("NORMAL");
            }
        }
        return toAjax(attendanceRecordService.updateAttendanceRecord(todayRecord));
    }




    /**
     * 获取今日考勤状态
     */

//    @GetMapping("/todayStatus")
//    public AjaxResult getTodayStatus() {
//        Long userId = SecurityUtils.getUserId();
//        logger.info("当前用户 ID: {}", userId);
//        AttendanceRecord record = attendanceRecordService.selectTodayRecordByUserId(userId);
//        logger.info("查询到的考勤记录: {}", record);
//
//        if (record == null) {
//            return success().put("status", "NOT_CHECKED_IN");
//        }
//
//        String status = record.getStatus();
//        if (status != null) {
//            return success(status);
//        }
//
//        if (record.getCheckOutTime() == null) {
//            return success("CHECKED_IN");
//        }
//        return success().put("status", record.getStatus() != null ? record.getStatus() : "CHECKED_IN");
////        return success("CHECKED_OUT");
//    }

    //    -----------------------------------------------------------
    @PreAuthorize("@ss.hasPermi('system:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(AttendanceRecord attendanceRecord) {
        startPage();
        List<AttendanceRecord> list = attendanceRecordService.selectAttendanceRecordList(attendanceRecord);
        return getDataTable(list);
    }


    @Log(title = "更新考勤备注", businessType = BusinessType.UPDATE)
    @PutMapping("/updateRemark")
    public AjaxResult updateRemark(@RequestBody AttendanceRecord attendanceRecord) {
        try {
            logger.info("收到备注更新请求，记录ID：{}，用户ID：{}",
                    attendanceRecord.getId(),
                    SecurityUtils.getUserId());

            if (attendanceRecord.getId() == null) {
                return error("缺少考勤记录ID");
            }

            AttendanceRecord existRecord = attendanceRecordService.selectAttendanceRecordById(attendanceRecord.getId());
            if (existRecord == null) {
                return error("考勤记录不存在");
            }

            if (!existRecord.getUserId().equals(SecurityUtils.getUserId())) {
                return error("无权修改他人记录");
            }

            // 仅更新备注字段
            existRecord.setNotes(attendanceRecord.getNotes());
            int result = attendanceRecordService.updateAttendanceRecord(existRecord);

            if (result > 0) {
                logger.info("记录{}更新成功", attendanceRecord.getId());
                return success();
            }
            return error("更新失败");
        } catch (Exception e) {
            logger.error("更新备注异常：", e);
            return error("服务器内部错误");
        }
    }

    // 修改今日状态接口返回完整记录
    @GetMapping("/todayStatus")
    public AjaxResult getTodayStatus() {
        try {

        Long userId = SecurityUtils.getUserId();
        System.out.println(userId);
        AttendanceRecord record = attendanceRecordService.selectTodayRecordByUserId(userId);

        if (record == null) {
            return success().put("status", "NOT_CHECKED_IN");
        }
        // 返回包含ID的完整记录
        return success()
                .put("status", record.getStatus())
                .put("id", record.getId())
                .put("data", record)
                .put("notes", record.getNotes());
        }catch (Exception e) {
            e.printStackTrace();
            return error("接口异常");
        }
    }

//        Long userId = SecurityUtils.getUserId();
//        attendanceRecord.setUserId(userId);
//        return toAjax(attendanceRecordService.updateAttendanceRecord(attendanceRecord));

}